angular.module 'wf-tab', ['ionic']

.directive 'wfTab', (tabData, $ionicHistory, $state) ->
    restrict: 'A'
    link: ($scope, $element, $attrs) ->
        fakeEle = angular.element document.createDocumentFragment()
        fakeEle.append '<div class="tabs tab-nav tabs-icon-top tabs-stable"></div>'
        clearOldTab = undefined # 用于清除旧tab上的样式

        # 处理Tab的DOM元素
        _.each tabData, (tab, $index) ->
            console.log tab.state
            if tab.state == 'tab.kefu'
                fakeEle.children().append """
                  <a class="tab-item big" idx="#{$index}"
                    state="#{tab.state}">
                    <i class="icon #{tab.iconOff}"></i>
                    <span class='chat-bubble' style="display:none;position: absolute;background: #f73e05;border-radius: 100px;
                        color: white;width: 13px;height: 13px;margin-left: 7px;margin-top: -29px;"></span>
                    <span>#{tab.title}</span>
                  </a>
                """
            else
                fakeEle.children().append """
                  <a class="tab-item" idx="#{$index}"
                    state="#{tab.state}">
                    <i class="icon #{tab.iconOff}"></i><span>#{tab.title}</span></a>
                """
        $element.append fakeEle

        innerElement = angular.element _.last($element.children())

        # 设置tab高亮区域
        select = (idx) ->
            if clearOldTab != undefined then clearOldTab()
            ele = angular.element innerElement.children()[idx]
            iEle = ele.children()
            iEle.removeClass tabData[idx].iconOff
            iEle.addClass tabData[idx].iconOn

            clearOldTab = ->
                iEle.removeClass tabData[idx].iconOn
                iEle.addClass tabData[idx].iconOff

        stateName = $state.current.name
        idx = _.findIndex tabData, (tab) -> tab.state == stateName
        if idx != -1 then select idx

        # 为ion-content添加bottom，保证底部不被Tab遮住
        ionContent = _.find $element.children(), (ele) -> ele.tagName == 'ION-CONTENT'
        height = innerElement[0].getClientRects()[0].height # 获取tab高度
        ionContent.style.bottom = "#{height + 1}px"

        # 点击跳转页面
        innerElement.bind 'click', (e) ->
            tagName = e.target.tagName 
            if tagName != 'DIV'
                ele = angular.element e.target
                if tagName in ['SPAN', 'I'] then ele = ele.parent()
#                if tagName == 'SPAN' then ele = ele.parent()
                state = ele.attr 'state' # 获取待跳转的state
                if state == $state.current.name
                    return

                if state == 'tab.kefu'
                    #todo 做一个事件，通知弹出客服窗口，客服窗口写成一个公用类。判断是否登录来给客服发送消息。
                    $scope.$emit('kefu', 'show')
                    return
                if !state
                    console.log ele
                $ionicHistory.nextViewOptions {disableBack: true}
                $state.go state
